package com.pinyoumei.app.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.pinyoumei.app.utils.DpUtils;


/**
 * @author xiayiye5
 * 2020年11月14日15:21:42
 * 自定义圆角图片
 */
@SuppressLint("AppCompatCustomView")
public class RadiuImageView extends ImageView {

    /**
     * 圆角大小
     */
    private int radiusSize = DpUtils.dip2px(getContext(), 15);

    public RadiuImageView(Context context) {
        super(context, null);
    }

    public RadiuImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public RadiuImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
    }

    /**
     * 设置圆角大小,设置后需要再次刷新下当前view，使用invalidate()或者postInvalidate()刷新都可以的
     *
     * @param size dp值
     */
    public void setRadiusSize(int size) {
        radiusSize = DpUtils.dip2px(getContext(), size);
        invalidate();
//        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getWidth() > radiusSize && getHeight() > radiusSize) {
            @SuppressLint("DrawAllocation")
            Path path = new Path();
            path.moveTo(radiusSize, 0);
            path.lineTo(getWidth() - radiusSize, 0);
            path.quadTo(getWidth(), 0, getWidth(), radiusSize);
            path.lineTo(getWidth(), getHeight() - radiusSize);
            path.quadTo(getWidth(), getHeight(), getWidth() - radiusSize, getHeight());
            path.lineTo(radiusSize, getHeight());
            path.quadTo(0, getHeight(), 0, getHeight() - radiusSize);
            path.lineTo(0, radiusSize);
            path.quadTo(0, 0, radiusSize, 0);
            canvas.clipPath(path);
        }
        super.onDraw(canvas);
    }
}

